/**
 * 
 */
package com.hahaduo.bee.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hahaduo.bee.dao.entity.File;
import com.hahaduo.bee.domain.Message;
import com.hahaduo.bee.domain.StatusResponse;
import com.hahaduo.bee.domain.UploadedFile;
import com.hahaduo.bee.mybatis.persistence.FileMapper;

/**
 * @author noodles.wumu@gmail.com
 * @since 2013/07/01 16:49:32
 * @version 0.1
 */

@Controller
@RequestMapping(value = "/files")
public class FileController {

	@Resource
	private FileMapper fm;
	/**
	 * VIEW PATH
	 */
	private static final String PATH_PREFIX = "file/";

	@RequestMapping(value = "/json", method = RequestMethod.GET)
	public @ResponseBody List<File> list() throws Exception {
		List<File> file = fm.getList();
		return file;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String list(ModelMap model) throws Exception {
		List<File> file = fm.getList();

		model.put("fileList", file);
		return PATH_PREFIX + "list";
	}

	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void download(@NotNull @RequestParam("id") long id,
			HttpServletRequest req, HttpServletResponse res) {

		File file = fm.getById(id);

		res.setContentType(file.getContentType());
		OutputStream out = null;
		try {
			String fileName = URLEncoder.encode(file.getName(), "UTF-8");
			fileName = URLDecoder.decode(fileName, "ISO8859_1");
			res.setHeader("Content-Disposition", "attachment; filename="
					+ fileName);
			out = res.getOutputStream();
			out.write(file.getContents());
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String getUploadPage() {
		return PATH_PREFIX + "upload";
	}

	@RequestMapping(value = "/message", method = RequestMethod.POST)
	public @ResponseBody StatusResponse message(@RequestBody Message message) {
		// Do custom steps here
		// i.e. Persist the message to the database

		return new StatusResponse(true, "Message received");
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody List<UploadedFile> handleFileUpload(
			@RequestParam("file") MultipartFile file) throws IOException {

		if (!file.isEmpty()) {

			saveFile(file);
		}

		List<UploadedFile> uploadedFiles = new ArrayList<UploadedFile>();
		UploadedFile u = new UploadedFile(file.getOriginalFilename(), Long
				.valueOf(file.getSize()).intValue(),
				"//"
						+ file.getOriginalFilename());

		uploadedFiles.add(u);
		return uploadedFiles;

	}

	@RequestMapping(value = "/uploadMulti", method = RequestMethod.POST)
	public String handleFileUpload(@RequestParam("files") MultipartFile[] files)
			throws IOException {
		for (MultipartFile file : files) {
			if (!file.isEmpty()) {
				saveFile(file);
			}

		}
		return "redirect:";
	}

	private void saveFile(MultipartFile file) throws IOException {
		File f = new File();
		f.setContents(file.getBytes());
		f.setContentType(file.getContentType());
		f.setName(file.getOriginalFilename());
		f.setExtension(FilenameUtils.getExtension(file.getOriginalFilename()));
		f.setSize(file.getSize());

		fm.insert(f);
	}

	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public String delete(@NotNull @RequestParam("id") long id)
			throws IOException {

		fm.delete(id);
		return "redirect:";

	}
}
